/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.excesys.exsecs.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.vo.ErrorMessage;
import com.excesys.exsecs.om.dto.PointDto;
import com.excesys.exsecs.om.entity.OmICheckPoint;
import com.excesys.exsecs.om.entity.OmIPointAssetRel;
import com.excesys.exsecs.om.mapper.OmICheckPointMapper;
import com.excesys.exsecs.om.mapper.OmIPointAssetRelMapper;
import com.excesys.exsecs.om.mapper.OmInspectionAreaMapper;
import com.excesys.exsecs.om.service.OmICheckPointService;
import com.excesys.exsecs.om.vo.PointExcelVo;
import com.excesys.exsecs.om.vo.PointVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 巡检点位表
 *
 * @author weiyj
 * @date 2023-03-01 14:10:58
 */
@Service
@RequiredArgsConstructor
public class OmICheckPointServiceImpl extends ServiceImpl<OmICheckPointMapper, OmICheckPoint>
		implements OmICheckPointService {

	private final OmIPointAssetRelMapper omIPointAssetRelMapper;

	private final OmInspectionAreaMapper omInspectionAreaMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean savePoint(PointDto pointDto) {

		OmICheckPoint omICheckPoint = new OmICheckPoint();
		BeanUtils.copyProperties(pointDto, omICheckPoint);
		if (StringUtil.isNotEmpty(pointDto.getNfcStr())) {
			if (baseMapper.getList(pointDto).size() > 0) {
				return Boolean.FALSE;
			}
		}
		baseMapper.insert(omICheckPoint);
		// 保存用户岗位信息
		Optional.ofNullable(pointDto.getRelList()).ifPresent(relLists -> {
			relLists.stream().map(omIPointAssetRel -> {
				omIPointAssetRel.setPointId(omICheckPoint.getIpId());
				return omIPointAssetRel;
			}).forEach(omIPointAssetRelMapper::insert);
		});
		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updatePoint(PointDto pointDto) {

		OmICheckPoint omICheckPoint = new OmICheckPoint();
		BeanUtils.copyProperties(pointDto, omICheckPoint);
		omICheckPoint.setUpdateTime(LocalDateTime.now());
		// if(StringUtil.isNotEmpty(pointDto.getNfcStr())) {
		// if (baseMapper.getList(omICheckPoint).size() > 0) {
		// return false;
		// }
		// }
		this.updateById(omICheckPoint);
		omIPointAssetRelMapper
				.delete(Wrappers.<OmIPointAssetRel>lambdaQuery().eq(OmIPointAssetRel::getPointId, pointDto.getIpId()));
		// 保存用户岗位信息
		Optional.ofNullable(pointDto.getRelList()).ifPresent(relLists -> {
			relLists.stream().map(omIPointAssetRel -> {
				omIPointAssetRel.setPointId(omICheckPoint.getIpId());
				return omIPointAssetRel;
			}).forEach(omIPointAssetRelMapper::insert);
		});
		return true;
	}

	@Override
	public Boolean removePointById(OmICheckPoint omICheckPoint) {
		omIPointAssetRelMapper.delete(
				Wrappers.<OmIPointAssetRel>lambdaQuery().eq(OmIPointAssetRel::getPointId, omICheckPoint.getIpId()));
		this.removeById(omICheckPoint.getIpId());
		return Boolean.TRUE;
	}

	/**
	 * 分页查询用户信息（含有角色信息）
	 * @param page 分页对象
	 * @param pointDto 参数列表
	 * @return
	 */
	@Override
	public IPage<PointVo> getPointWithRelPage(Page page, PointDto pointDto) {
		return baseMapper.getPointWithRelPage(page, pointDto);
	}

	@Override
	public Map<String, String> getPointCountMap() {
		return this.getBaseMapper().getPointCountMap();
	}

	@Override
	public List<PointExcelVo> listBamSBuildings() {
		List<OmICheckPoint> bamSBuildings = this.list(Wrappers.emptyWrapper());
		// 转换成execl 对象输出
		return bamSBuildings.stream().map(buildings -> {
			PointExcelVo pointExcelVo = new PointExcelVo();
			BeanUtil.copyProperties(buildings, pointExcelVo);
			return pointExcelVo;
		}).collect(Collectors.toList());
	}

	@Override
	public R importBamSBuildings(List<PointExcelVo> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
		int sucess = 0;
		int fail = 0;

		// 执行数据插入操作 组装 RoleDto
		for (PointExcelVo excel : excelVOList) {
			// 个性化校验逻辑
			List<OmICheckPoint> postList = this.list();
			// 检验区域或者NFC编码是否存在
			Set<String> errorMsg = new HashSet<>();
			boolean existPost = postList.stream().anyMatch(
					post -> excel.getAreaNo().equals(post.getAreaNo()) || excel.getNfcStr().equals(post.getNfcStr()));
			if (existPost) {
				errorMsg.add("区域或者NFC编码存在重复" + excel.getAreaNo() + "," + excel.getNfcStr());
			}

			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				int num = insertBamSBuildings(excel);
				if (num == 1) {
					fail++;
				}
				else {
					sucess++;
				}
			}
			else {
				// 数据不合法情况
				errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
			}
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok(sucess, "成功导入数量" + sucess + "。" + "存在" + fail + "重复");
	}

	private int insertBamSBuildings(PointExcelVo excel) {
		OmICheckPoint omICheckPoint = new OmICheckPoint();
		omICheckPoint.setPointName(excel.getPointName());
		// omICheckPoint.setPointDesc(excel.getPointDesc());
		omICheckPoint.setAreaNo(excel.getAreaNo());
		omICheckPoint.setPointPosition(excel.getPointPosition());
		omICheckPoint.setPointStatus(excel.getPointStatus());
		// omICheckPoint.setWorkStatus(excel.getWorkStatus());
		omICheckPoint.setNfcStr(excel.getNfcStr());
		// omICheckPoint.setNfcStatus(excel.getNfcStatus());
		omICheckPoint.setPointDesc(excel.getPointDesc());
		this.save(omICheckPoint);
		return 0;
	}

}
